﻿/*===================================================
* CLR版本  : 4.0.30319.42000 
* 类名称   : ObjectPool
* 文 件 名 : ObjectPool 
* 类描述   :
* 创建人   : oream
* 创建时间 : 2018/2/13 16:42:41
* 修改人   : 
* 修改时间 :
* 版本： @version 1.0
=====================================================*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Hotfix
{
  public sealed class ObjectPool
  {
    private readonly Dictionary<Type, Queue<Disposer>> dicObjectPool = new Dictionary<Type, Queue<Disposer>>();

    /// <summary>
    /// 获取对象池对象
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public Disposer FetchObject(Type type)
    {
      Queue<Disposer> disposerQueue;
      if (!dicObjectPool.TryGetValue(type, out disposerQueue))
      {
        disposerQueue = new Queue<Disposer>();
        dicObjectPool.Add(type, disposerQueue);
      }
      Disposer disposer = null;
      if (disposerQueue.Count > 0)
      {
        disposer = disposerQueue.Dequeue();
        disposer.id = IDHellper.ProduceID();
        return disposer;
      }
      disposer = Activator.CreateInstance(type) as Disposer;
      disposerQueue.Enqueue(disposer);
      return disposer;
    }

    /// <summary>
    /// 获取对象池对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T FetchObject<T>() where T : Disposer
    {
      return (T)this.FetchObject(typeof(T));
    }


  }
}
